package org.inote.controller;

import org.inote.common.KeyStatus;
import org.inote.common.StatusConst;
import org.inote.pojo.tablePojo.User;
import org.inote.service.UserService;
import org.inote.utils.DateFormatUtil;
import org.inote.utils.FileUploadUtil;
import org.inote.utils.PhoneCodeUtil;
import org.inote.utils.StringFormUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * 用户相关操作
 * @author HUAWEI
 */
@Controller
@RequestMapping("/user")
public class UserController {

    /**
     * 变量名：用户信息（存放User对象）
     */
    public static final String USER_INFO = "userInfo";
    /**
     * 变量名：注册业务手机号
     */
    public static final String REGISTER_PHONE = "registerPhone";

    /**
     * 变量名：登录业务手机号
     */
    public static final String LOGIN_PHONE = "loginPhone";

    /**
     * 变量名：注册业务手机验证码
     */
    public static final String REGISTER_CODE = "registerCode";

    /**
     * 变量名：登录业务手机验证码
     */
    public static final String LOGIN_CODE = "loginCode";

    /**
     * 变量名：登录状态
     */
    public static final String LOG_STATUS = "logStatus";

    /**
     * 变量值/执行结果：已登录
     */
    public static final String LOG_IN = "logIn";

    /**
     * 变量值/执行结果：未登录
     */
    public static final String LOG_OFF = "logOff";

    /**
     * 执行结果：手机号不合法
     */
    public static final String NOT_PHONE = "notPhone";

    /**
     * 执行结果：前后手机号不一致
     */
    public static final String DIF_PHONE = "difPhone";

    /**
     * 执行结果：密码不合法
     */
    public static final String NOT_PASSWORD = "notPassword";

    /**
     * 执行结果：密码错误
     */
    public static final String ERROR_PASSWORD = "errorPassword";

    /**
     * 执行结果：验证码错误
     */
    public static final String ERROR_CODE = "errorCode";

    /**
     * 执行结果：手机号已被注册
     */
    public static final String PHONE_EXIST = "phoneExist";

    /**
     * 执行结果：手机号未被注册
     */
    public static final String PHONE_NOT_EXIST = "phoneNotExist";

    UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }


    /**
     * 检测手机号是否已被注册
     * @param phone
     * @return
     * 1."nullVar"：手机号为空
     * 2."notPhone"：手机号格式错误
     * 3."phoneExist"：手机号已被注册
     * 4."true"：手机号可行
     */
    @ResponseBody
    @RequestMapping("/checkPhone")
    public String checkPhone(String phone){
        if (StringFormUtil.isEmpty(phone)){
            return StatusConst.NULL_VAR;
        }
        if (!StringFormUtil.isPhone(phone)){
            return NOT_PHONE;
        }
        boolean exist = userService.phoneExist(phone);
        if (exist){
            return PHONE_EXIST;
        }
        return StatusConst.TRUE;
    }


    /**
     * 发送注册验证码
     * @param registerPhone
     * @param session
     * @return
     * 1."nullVar"：手机号为空
     * 2."notPhone"：手机号格式错误
     * 3."true"：验证码发送成功
     * 存入session中的数据：
     * 1."registerCode"：验证码
     * 2."registerPhone"：手机号
     */
    @ResponseBody
    @RequestMapping("/sendRegisterCode")
    public String sendRegisterCode(String registerPhone, HttpSession session){
        if (StringFormUtil.isEmpty(registerPhone)){
            return StatusConst.NULL_VAR;
        }
        if (!StringFormUtil.isPhone(registerPhone)){
            return NOT_PHONE;
        }
        String registerCode = PhoneCodeUtil.sendPhoneCode(registerPhone);
        session.setAttribute(REGISTER_CODE, registerCode);
        session.setAttribute(REGISTER_PHONE, registerPhone);
        return StatusConst.TRUE;
    }


    /**
     * 手机号注册账号，方法执行完毕后session中的手机号和验证码会被清空，需要重新发送验证码
     * @param registerPhone
     * @param password
     * @param registerCode
     * @param session
     * @return
     * 1."nullVar"：参数有空值
     * 2."notPhone"：手机号不合法
     * 3."notPassword"：密码不合法
     * 4."difPhone"：前后手机号不一致
     * 5."errorCode"：验证码错误
     * 6."phoneExist"：手机号已被注册
     * 7."true"：注册成功
     */
    @ResponseBody
    @RequestMapping("/register")
    public String register(String registerPhone, String password, String registerCode, HttpSession session){
        String result = StatusConst.TRUE;
        String realPhone = (String) session.getAttribute(REGISTER_PHONE);
        String realCode = (String) session.getAttribute(REGISTER_CODE);
        boolean success = userService.register(registerPhone, password);
        if (StringFormUtil.isEmpty(registerPhone, password, registerCode)){
            result = StatusConst.NULL_VAR;
        }else if (!StringFormUtil.isPhone(registerPhone)){
            result = NOT_PHONE;
        }else if (!StringFormUtil.isPassword(password)){
            result = NOT_PASSWORD;
        }else if (!registerPhone.equals(realPhone)){
            result = DIF_PHONE;
        }else if (!registerCode.equals(realCode)){
            result = ERROR_CODE;
        }else if (success == false){
            result = PHONE_EXIST;
        }
        if (result!=StatusConst.TRUE){
            return result;
        }
        session.setAttribute(REGISTER_PHONE, "");
        session.setAttribute(REGISTER_CODE, "");
        return result;
    }

    /**
     * 发送登录验证码
     * @param loginPhone
     * @param session
     * @return
     * 1."nullVar"：手机号为空
     * 2."notPhone"：手机号非法
     * 3."true"：验证码发送成功
     * 存入session中的数据：
     * 1."loginCode"：登录验证码
     * 2."loginPhone"：登录手机号
     */
    @ResponseBody
    @RequestMapping("/sendLoginCode")
    public String sendLoginCode(String loginPhone, HttpSession session){
        if (StringFormUtil.isEmpty()){
            return StatusConst.NULL_VAR;
        }
        if (!StringFormUtil.isPhone(loginPhone)){
            return NOT_PHONE;
        }
        String loginCode = PhoneCodeUtil.sendPhoneCode(loginPhone);
        session.setAttribute(LOGIN_CODE, loginCode);
        session.setAttribute(LOGIN_PHONE, loginPhone);
        return StatusConst.TRUE;
    }

    /**
     * 验证码登录
     * @param loginPhone
     * @param loginCode
     * @param session
     * @return
     * 1."nullVar"：参数存在空值
     * 2."notPhone"：手机号不合法
     * 3."difPhone"：手机号不一致
     * 4."errorCode"：验证码错误
     * 5."phoneNotExist"：手机号未注册
     * 存入session中的参数：
     * 1."userInfo"：用户信息
     */
    @ResponseBody
    @RequestMapping("/loginByCode")
    public String loginByCode(String loginPhone, String loginCode, HttpSession session){
        String result = StatusConst.TRUE;
        String realPhone = (String) session.getAttribute(LOGIN_PHONE);
        String realCode = (String) session.getAttribute(LOGIN_CODE);
        boolean exist = userService.phoneExist(loginPhone);
        if (StringFormUtil.isEmpty(loginPhone, loginCode)){
            result = StatusConst.NULL_VAR;
        }else if (!StringFormUtil.isPhone(loginPhone)){
            result = NOT_PHONE;
        }else if (!loginPhone.equals(realPhone)){
            result = DIF_PHONE;
        }else if (!loginCode.equals(realCode)){
            result = ERROR_CODE;
        }else if (exist == false){
            result = PHONE_NOT_EXIST;
        }
        if (result!=StatusConst.TRUE){
            return result;
        }

        User user = userService.getUser(loginPhone);
        session.setAttribute(USER_INFO, user);
        session.setAttribute(LOGIN_PHONE, "");
        session.setAttribute(LOGIN_CODE, "");
        return result;
    }

    /**
     * 密码登录
     * @param loginPhone
     * @param password
     * @param session
     * @return
     * 1."nullVar"：参数存在空值
     * 2."notPhone"：手机号为空
     * 3."notPassword"：密码格式错误
     * 4."phoneNotExist"：该手机号未注册
     * 5."errorPassword"：密码错误
     * 存入session中的参数：
     * 1."userInfo"：用户信息
     */
    @ResponseBody
    @RequestMapping("/loginByPassword")
    public String loginByPassword(String loginPhone, String password, HttpSession session){
        User user = userService.getUser(loginPhone);

        if (StringFormUtil.isEmpty(loginPhone, password)){
            return StatusConst.NULL_VAR;
        }else if (!StringFormUtil.isPhone(loginPhone)){
            return NOT_PHONE;
        }else if (!StringFormUtil.isPassword(password)){
            return NOT_PASSWORD;
        }else if (user==null){
            return PHONE_NOT_EXIST;
        }else if (!user.getUserPassword().equals(password)){
            return ERROR_PASSWORD;
        }
        session.setAttribute(USER_INFO, user);
        return StatusConst.TRUE;
    }

    /**
     * 检查登录状态
     * @param session
     * @return
     * 1."logIn"：已登录
     * 2."logOff"：未登录
     */
    @ResponseBody
    @RequestMapping("/checkStatus")
    public String checkStatus(HttpSession session){
        User user = (User) session.getAttribute(USER_INFO);
        if (user==null){
            return LOG_OFF;
        }
        return LOG_IN;
    }

    /**
     * 更新用户信息
     * @param session
     * @return
     * 1."更新成功"
     * 存入session中的参数：
     * 1."userInfo"：更新后的用户数据
     */
    @ResponseBody
    @RequestMapping("/refreshUserInfo")
    public String refreshUserInfo(HttpSession session){
        User oldUser = (User) session.getAttribute(USER_INFO);
        User newUser = userService.getUser(oldUser.getUserPhone());
        session.setAttribute(USER_INFO, newUser);
        return StatusConst.TRUE;
    }

    /**
     * 更改密码
     * @param oldPassword
     * @param newPassword
     * @param session
     * @return
     * 1."logOff"：未登录
     * 2."nullVar"：参数存在空值
     * 3."errorPassword"：旧密码错误
     * 4."notPassword"：新密码不合法
     * 5."false"：更改失败
     * 6."true"：更改成功
     */
    @ResponseBody
    @RequestMapping("/changePassword")
    public String changePassword(String oldPassword, String newPassword, HttpSession session){
        System.out.println(oldPassword);
        System.out.println(newPassword);
        User user = (User) session.getAttribute(USER_INFO);
        if (user==null){
            return LOG_OFF;
        }
        String realPassword = user.getUserPassword();
        if (StringFormUtil.isEmpty(oldPassword, newPassword)){
            return StatusConst.NULL_VAR;
        }
        if (!oldPassword.equals(realPassword)){
            return ERROR_PASSWORD;
        }
        if (!StringFormUtil.isPassword(newPassword)){
            return NOT_PASSWORD;
        }
        boolean result = userService.updatePasswordById(user.getUserId(), newPassword);
        if (!result){
            return StatusConst.FALSE;
        }
        return StatusConst.TRUE;
    }
    

    /**
     * 编辑用户资料
     * @param edit_name
     * @param edit_image
     * @param edit_date
     * @param session
     * @return
     */
    @RequestMapping("/editUser")
    public String editUserInfo(String edit_name, MultipartFile edit_image, String edit_date, HttpSession session){
        //获取当前登录用户信息
        User user = (User) session.getAttribute("userInfo");
        System.out.println(user.toString());
        if(edit_name != null){
            user.setUserName(edit_name);
        }
        if(edit_date != null){
            Date date = DateFormatUtil.dataFormat(edit_date);
            System.out.println(date);
            user.setUserDate(date);
            System.out.println("你是傻逼");
        }
        String dirPath = session.getServletContext().getRealPath("/upload/");
        String type = KeyStatus.USER_IMG;

        String image_String = "/upload/";
        image_String += FileUploadUtil.uploadImage(edit_image,dirPath,user.getUserPhone(),type);

        if(image_String != null)
            user.setUserImg(image_String);
        userService.updateUser(user);
        return "redirect:/enterMyHome";
    }

}
